import React from 'react';
import { Chart, Tooltip, Geom, Legend, Axis, Label } from 'bizcharts';
import DataSet from '@antv/data-set';
import Slider from 'bizcharts-plugin-slider';
import autoHeight from '../autoHeight';
import styles from './index.less';

@autoHeight()
class TimelineChartFour extends React.Component {
  render() {
    const {
      tickInterval,
      yMin = 0,
      title,
      height = 500,
      padding = [50, 40, 70, 50],
      titleMap = {
        y1: 'y1',
        y2: 'y2',
      },
      borderWidth = 2,
      data: sourceData,
    } = this.props;

    const data = Array.isArray(sourceData) ? sourceData : [{ x: 0, y1: 0, y2: 0 }];

    data.sort((a, b) => a.x - b.x);

    let max;
    if (data[0] && data[0].y1 && data[0].y2) {
      max = Math.max(
        [...data].sort((a, b) => b.y1 - a.y1)[0].y1,
        [...data].sort((a, b) => b.y2 - a.y2)[0].y2
      );
    }

    let min;
    if (data[0] && data[0].y1 && data[0].y2) {
      min = Math.min(
        [...data].sort((a, b) => a.y1 - b.y1)[0].y1,
        [...data].sort((a, b) => a.y2 - b.y2)[0].y2
      );
    }

    const ds = new DataSet({
      state: {
        start: data[0].x,
        end: data[data.length - 1].x,
      },
    });

    const dv = ds.createView();
    dv.source(data)
      .transform({
        type: 'filter',
        callback: obj => {
          const date = obj.x;
          return date <= ds.state.end && date >= ds.state.start;
        },
      })
      .transform({
        type: 'map',
        callback(row) {
          const newRow = { ...row };
          newRow[titleMap.y1] = row.y1;
          newRow[titleMap.y2] = row.y2;
          return newRow;
        },
      })
      .transform({
        type: 'fold',
        fields: [titleMap.y1, titleMap.y2], // 展开字段集
        key: 'key', // key字段
        value: 'value', // value字段
      });
    // 此处修改了显示成  年月日  5天隔一次显示
    const timeScale = {
      type: 'cat',
      tickCount: 10,
      // tickInterval: 10,
      // mask: 'HH:mm',
      mask: 'YYYY-MM-DD',
      range: [0, 1],
    };

    const cols = {
      x: timeScale,
      value: {
        max,
        min,
      },
    };

    const SliderGen = () => (
      <Slider
        padding={[0, padding[1] + 60, 0, padding[3] + 40]}
        // padding={[0, padding[1] + 20, 0, padding[3]+ 0]}
        width="auto"
        height={26}
        xAxis="x"
        yAxis="y1"
        scales={{ x: timeScale }}
        data={data}
        start={ds.state.start}
        end={ds.state.end}
        backgroundChart={{ type: 'line' }}
        onChange={({ startValue, endValue }) => {
          ds.setState('start', startValue);
          ds.setState('end', endValue);
        }}
      />
    );

    const lastData = data[data.length - 1];
    let lastDataFlag = true;
    return (
      <div className={styles.timelineChart} style={{ height: height + 30 }}>
        <div>
          {title && <h4>{title}</h4>}
          <Chart height={height} padding={padding} data={dv} scale={cols} renderer="svg" forceFit>
            <Axis name="x" />
            <Tooltip />
            <Legend
              name="key"
              position="top"
              useHtml
              itemTpl={() => {
                if (titleMap.y2) {
                  let lastDataY = 0;
                  if (lastDataFlag) {
                    lastDataY = lastData.y1;
                    lastDataFlag = false;
                  } else {
                    lastDataY = lastData.y2;
                    lastDataFlag = true;
                  }
                  return (
                    `${'<li class="g2-legend-list-item item-{index} {checked}" data-color="{originColor}" data-value="{originValue}" style="cursor: pointer;font-size: 12.5px;display: inline-block;">' +
                      '<i class="g2-legend-marker" style="width:8px;height:8px;border-radius:30%;display:inline-block;margin-right:10px;background-color: {color};"></i>' +
                      '<span class="g2-legend-text">{value}' +
                      ': '}${lastDataY}</span>` +
                    `<div style=" width:100px;height:30px;"/>` +
                    `</li>`
                  );
                }
                return (
                  `${'<li class="g2-legend-list-item item-{index} {checked}" data-color="{originColor}" data-value="{originValue}" style="cursor: pointer;font-size: 12.5px;display: inline-block;">' +
                    '<i class="g2-legend-marker" style="width:8px;height:8px;border-radius:30%;display:inline-block;margin-right:10px;background-color: {color};"></i>' +
                    '<span class="g2-legend-text">{value}' +
                    ': '}${lastData.y1}</span>` +
                  `<div style=" width:100px;height:30px;"/>` +
                  `</li>`
                );
              }}
            />
            {/* ({value} ==='spy净值'?lastData.y2||lastData.y1)+*/}
            <Axis name="y1" visible position="left" />
            {/*   <Label
              content={"value"}
              offset={10}
              htmlTemplate={(text, item, index)=>{
                if(data.langth-1 === index){
                  return'<div><div>'+
                    'y1:'+item.point.y1+'</div><div>'+'y2:'+item.point.y2+'</div></div>';
                }
              }}/> */}
            {titleMap.y2 ? (
              <Geom
                type="line"
                position="x*value"
                size={borderWidth}
                color={['key', ['#4e81bd', '#c1504c']]}
              />
            ) : (
              <Geom
                type="line"
                position="x*y1"
                size={borderWidth}
                color={['key', ['#4e81bd']]}
                tooltip={[
                  'x*y1',
                  (x, y1) => {
                    return {
                      name: titleMap.y1,
                      value: y1,
                    };
                  },
                ]}
              />
            )}
            {/* <Axis name="y2" visible={true} position={'left'}/> */}
          </Chart>
        </div>
      </div>
    );
  }
}

export default TimelineChartFour;
